package com.ehualu.esresult;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ehualu.esresult.utils.HttpUtil;

/**
 * @Author: 吴敬超
 * @Date: 2020/7/8 16:01
 */
public class ESpost {


    public static void main(String[] args) {

        String url = "http://192.168.22.8:9200/exp-vehicle-realtime/_search";


        String josn = "{\n" +
                "    \"size\": 0,\n" +
                "    \"aggs\": {\n" +
                "        \"top_tags\": {\n" +
                "            \"terms\": {\n" +
                "                \"field\": \"id.keyword\"\n" +
                "            },\n" +
                "            \"aggs\": {\n" +
                "                \"top_sales_hits\": {\n" +
                "                    \"top_hits\": {\n" +
                "                        \"sort\": [\n" +
                "                            {\n" +
                "                                \"time\": {\n" +
                "                                    \"order\": \"desc\"\n" +
                "                                }\n" +
                "                            }\n" +
                "                        ],\n" +
                "                        \"_source\": {\n" +
                "                            \"includes\": [\n" +
                "                                \"time\",\n" +
                "                                \"speed\",\n" +
                "                                \"Lng\",\n" +
                "                                \"Lat\",\n" +
                "                                \"battery_info\"\n" +
                "                            ]\n" +
                "                        },\n" +
                "                        \"size\": 1\n" +
                "                    }\n" +
                "                }\n" +
                "            }\n" +
                "        }\n" +
                "    }\n" +
                "}";

        String result = HttpUtil.HttpPostWithJson(url, josn);

        System.out.println(result);


        /*递归解析，解析到桶，结果转成JSONArray格式*/
        JSONArray jsonArray = JSON.parseObject(result)
                .getJSONObject("aggregations")
                .getJSONObject("top_tags")
                .getJSONArray("buckets");

        /*遍历桶*/
        for (int i = 0; i < jsonArray.size(); i++) {

            JSONObject buckets = jsonArray.getJSONObject(i);

            /*每个桶内结果解析，解析到_source*/
            String source = buckets
                    .getJSONObject("top_sales_hits")
                    .getJSONObject("hits")
                    .getJSONArray("hits")
                    .getJSONObject(0)
                    .getString("_source");


            System.out.println("*****source****" + source);
        }


    }


}
